<?php

/**
 * Description of xPipe
 *
 * @author chedim
 */

class xIoPipe implements xIoPipeInterface {
    
    protected $buffer = array();
    protected $pipe_length = array();

    /**
     * @var xIoPipeInterface 
     */
    protected $target;
    protected $choke = false;
    protected $parent_name = '';
    protected $name = '';
    protected static $pipeCount = 0;
    
    public function  __construct($name, $length = 1, $choke = false, &$target = null) {
	$this->pipe_length = $length;
	$this->target = $target;
	$this->choke = $choke;
	$this->name = $name;
    }
    
    public function put($data) {
	$this->buffer[] = $data;
	if(count($this->buffer) > $this->pipe_length) {
	    if ($this->choke) {
		array_shift($this->buffer);
	    } elseif($this->target === null) {
		xIoPipeLeak::fire();
	    }
	    $this->target->put(array_shift($this->buffer));
	}
    }

    public function connect(xIoPipeInterface $target) {
	if ($this->target != null) {
	    throw new xIoPipeOccupied();
	}
	$this->target = $target;
    }

    public function connected(xIoPipeInterface $parent) {
	$this->parent_name = $parent->get_name();
    }

    public function is_connected() {
	return ($this->parent_name != '');
    }

    public function is_choke() {
	return (boolean) $this->choke;
    }

    public function is_occupied() {
	return $this->target !== null;
    }

}

?>
